from plyny.plio.files import File

import sys
import datetime
import json


class _base(object):
    def __init__(self, path):
        self._path = File(path)
        self._writer = None

    def write(self, value):
        if self._writer is None:
            self._writer = self._path.writer(append=True)

        self._writer.write(value)

    def read(self):
        for line in self._path:
            yield json.loads(line)


class usage(_base):
    def add_usage(self):
        self.write(json.dumps({
            'process': sys.argv[0],
            'date': str(datetime.datetime.now()),
            'args': sys.argv[1:]}) + '\n')

    def get(self):
        return list(self.read())
        

class config(_base):
    def __setattr__(self, key, value):
        if key in ('_path', '_writer'):
            super(config, self).__setattr__(key, value)
        else:
            if self._path.exists() and getattr(self, key) is not None:
                raise ValueError(key + ' already set')

            self.write(json.dumps({key: value}) + '\n')

    def __getattr__(self, key):
        if key in ('_path', '_writer'):
            super(config, self).__getattr__(key)
        else:
            for line in self.read():
                if key in line:
                    return line[key]


if __name__ == '__main__':
    from plyny.io.files import TemporaryDirectory
    t = TemporaryDirectory()
    c = config(t.path() / 'x')
    c.x = 'a'
    print c.x

    d = usage(t.path() / 'y')
    d.add_usage('me')
    print d.get()
